<template>
    <el-form :model="form" label-width="120px">
        <el-form-item label="姓名">
            <el-input v-model="form.teacherName" disabled />
        </el-form-item>
        <el-form-item label="权限">
            <el-select v-model="form.role">
                <el-option label="超级管理员" value="1"></el-option>
                <el-option label="教师" value="2"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="save">保存</el-button>
            <el-button @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import api from '@/api/teacher.ts';

const router = useRouter();
const route = useRoute();
const form = ref({
    teacherName: '',
    role: ''
});
const initialRole = ref('')

const change = async () => {
    const id = route.params.id;
    console.log("更改权限的id:" + id);
    try {
        const res = await api.findTeacherById({ teacherId: id });
        console.log("更改权限的user:" + JSON.stringify(res.data));
        form.value.teacherName = res.teacherName;
        initialRole.value=res.role;

        if(res.role===1){
            form.value.role='超级管理员'
        }else if(res.role===2){
            form.value.role = '教师'
        }
    } catch (error) {
        console.error('获取教师信息失败:', error);
    }
};

onMounted(() => {
    change()
});

const save = () => {
    if(initialRole.value == form.value.role){
        ElMessage.error('该用户已是该权限,请重新更改');
        return
    }
    api.updateTeacherRole(form.value)
    ElMessage.success('权限修改成功');
    router.push('/TeacherPage');
};

const cancel = () => {
    router.push('/TeacherPage');
};
</script>

<style scoped>
.el-form {
    width: 400px;
    margin: 20px auto;
}
</style>
